<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { Recordable } from '@vben/types';

import { computed, ref } from 'vue';

import { AuthenticationRegister, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { message } from 'ant-design-vue';

import { getCaptchaApi } from '#/api';
import { useAuthStore } from '#/store';

defineOptions({ name: 'Register' });
const authStore = useAuthStore();
const loading = ref(false);

const registerForm = ref();

const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: $t('authentication.usernameTip'),
      },
      fieldName: 'username',
      label: $t('authentication.username'),
      rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        passwordStrength: true,
        placeholder: $t('authentication.password'),
      },
      fieldName: 'password',
      label: $t('authentication.password'),
      renderComponentContent() {
        return {
          strengthText: () => $t('authentication.passwordStrength'),
        };
      },
      rules: z.string().min(1, { message: $t('authentication.passwordTip') }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: $t('authentication.confirmPassword'),
      },
      dependencies: {
        rules(values) {
          const { password } = values;
          return z
            .string({ required_error: $t('authentication.passwordTip') })
            .min(1, { message: $t('authentication.passwordTip') })
            .refine((value) => value === password, {
              message: $t('authentication.confirmPasswordTip'),
            });
        },
        triggerFields: ['password'],
      },
      fieldName: 'confirmPassword',
      label: $t('authentication.confirmPassword'),
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: $t('authentication.mobile'),
      },
      fieldName: 'phoneNumber',
      label: $t('authentication.mobile'),

      rules: z
        .string()
        .min(1, { message: $t('authentication.mobileTip') })
        .refine((v) => /^\d{11}$/.test(v), {
          message: $t('authentication.mobileErrortip'),
        }),
    },
    {
      component: 'VbenPinInput',
      componentProps: {
        createText: (countdown: number) => {
          const text =
            countdown > 0
              ? $t('authentication.sendText', [countdown])
              : $t('authentication.sendCode');
          return text;
        },

        placeholder: $t('authentication.code'),
        handleSendCode: async () => {
          const data = await registerForm?.value?.getValues();
          const mySchema = z
            .string()
            .min(1, { message: $t('authentication.mobileTip') })
            .refine((v) => /^\d{11}$/.test(v), {
              message: $t('authentication.mobileErrortip'),
            });
          try {
            mySchema.parse(data.phoneNumber);
            // 提交表单格式
            const getCodeFrom: any = await getCaptchaApi({
              phoneNumber: data.phoneNumber,
              sendType: 1,
            });
            if (getCodeFrom) {
              message.success('验证码已发送');
              return true;
            }
            throw new Error('完善信息', getCodeFrom);
          } catch (error: any) {
            // console.log('error', error);
            // [].includes;
            !error.includes('完善信息') && message.error('请输入正确手机号');
            throw new Error('完善信息', error);
          }
        },
      },
      // 触发获取验证码按钮
      fieldName: 'code',
      label: $t('authentication.code'),
      rules: z.string().min(1, { message: $t('authentication.codeTip') }),
    },
    // {
    //   component: 'VbenCheckbox',
    //   fieldName: 'agreePolicy',
    //   renderComponentContent: () => ({
    //     default: () =>
    //       h('span', [
    //         $t('authentication.agree'),
    //         h(
    //           'a',
    //           {
    //             class: 'vben-link ml-1 ',
    //             href: '',
    //           },
    //           `${$t('authentication.privacyPolicy')} & ${$t('authentication.terms')}`,
    //         ),
    //       ]),
    //   }),
    //   rules: z.boolean().refine((value) => !!value, {
    //     message: $t('authentication.agreeTip'),
    //   }),
    // },
  ];
});

function handleSubmit(value: Recordable<any>) {
  // console.log('register submit username:', value.username);
  // console.log('register submit password:', value.password);
  // console.log('register submit phoneNumber:', value.phoneNumber);
  // console.log('register submit code:', value.code);
  authStore.authRegisterAndLogin({
    username: value.username,
    password: value.password,
    phoneNumber: value.phoneNumber,
    phoneCode: value.code,
  });
  // registerApi().then((res) => {
  //   console.log('registerApi res:', res);
  // });
}
</script>

<template>
  <AuthenticationRegister
    ref="registerForm"
    :form-schema="formSchema"
    :loading="loading"
    @submit="handleSubmit"
  />
</template>
